import React, { useEffect, useState } from 'react'
import ProForm, {
  ModalForm,
  ProFormDigit,
  ProFormGroup,
  ProFormRadio,
  ProFormRate,
  ProFormText
} from '@ant-design/pro-form'
import { message, TreeSelect } from 'antd'
import EditorDemo from '@/components/Editor'
import Options from '@/pages/Exam/Question/components/Options'
import Radio from '@/pages/Exam/Question/components/type/Radio'
import Checkbox from '@/pages/Exam/Question/components/type/Checkbox'
import FillOrShort from '@/pages/Exam/Question/components/type/FillOrShort'
import Judge from '@/pages/Exam/Question/components/type/Judge'
import Subsystem from '@/pages/Exam/Question/components/type/Subsystem'
import { addExamQuestion, editExamQuestion } from '@/services/examquestion'

function Create (props) {
  const {
    isModalShow,
    setIsModalShow,
    type,
    typeQuestion,
    category,
    actionRef,
    questionDetails,
    subsystemId,
    DetailActionRef
  } = props
  /** 设置选择题选项 **/
  const [options, setOption] = useState(67)
  /** 设置 answer **/
  const [optionValues, setOptionValues] = useState({})
  /** 定义Form实例, 用来操作表单 **/
  const [formObj] = ProForm.useForm()

  useEffect(() => {
    if (questionDetails.answer !== undefined) {
      let answers = questionDetails.answer
      if (answers !== null) {
        setOption(Object.keys(answers)[Object.keys(answers).length - 1])
        formObj.setFieldsValue({ answer: answers })
      }
    }
  }, [typeQuestion, category])

  /**
   * 首字母大写
   * @param str
   * @returns {*}
   */
  const titleCase = (str) => {
    let newStr = str.split(' ')
    for (let i = 0; i < newStr.length; i++) {
      newStr[i] = newStr[i].slice(0, 1).toUpperCase() + newStr[i].slice(1).toLowerCase()
    }
    return newStr.join(' ')
  }

  const strComponents = typeQuestion === undefined ? typeQuestion : titleCase(typeQuestion)

  /**
   * 设置并获取副文本内容
   * @param content 内容
   * @param name 表单名称
   */
  const setDetails = (content, name) => {
    /** 设置answer选项 **/
    if (typeof name === 'number') {
      formObj.setFieldsValue({
        ...optionValues, answer: { ...{ [name]: content } }
      })
    }
    setOptionValues({ ...optionValues, ...{ [name]: content } })
  }

  /**
   * 处理选择题中的副文本编辑器
   * @returns {*[]}
   */
  const getOption = () => {
    let item = []
    for (let i = 65; i <= options; i++) {
      item.push(
        <Options
          name={i}
          key={i}
          options={i}
          getOptions={options}
          setOption={setOption}
          setDetails={setDetails}
          content={(questionDetails.answer === undefined || questionDetails.answer === null) ? '' : questionDetails.answer[i]}
        />
      )
    }
    return item
  }

  /**
   * 处理选择题中的正确答案
   * @returns {*[]}
   */
  const getOptions = () => {
    let array = []
    for (let j = 65; j <= options; j++) {
      array.push(
        {
          label: String.fromCharCode(j),
          value: j,
          key: j,
        }
      )
    }
    return array
  }

  /**
   * 添加题目
   * @param values
   */
  const createOrEditQuestion = async values => {
    // 对象合并
    let newValues = Object.assign(values, optionValues)

    let response = questionDetails.id === undefined ? await addExamQuestion(newValues) : await editExamQuestion(newValues)
    if (response === '') {
      //  刷新表格数据
      setIsModalShow(false)

      values.pid === undefined ? actionRef.current?.reload() : DetailActionRef.current?.reload()

      message.success((questionDetails.id === undefined ? `添加` : '修改') + '成功')
    }
  }

  /**
   * 定义组件
   * @type {{Radio: JSX.Element, undefined: string}}
   */
  const typeComponents = {
    undefined: '',
    'Radio': <Radio
      getOption={getOption}
      getOptions={getOptions}
      options={options}
      setOption={setOption}
      setDetails={setDetails}
      questionDetails={questionDetails}
    />,
    'Checkbox': <Checkbox
      getOption={getOption}
      getOptions={getOptions}
      options={options}
      setOption={setOption}
      setDetails={setDetails}
      questionDetails={questionDetails}
    />,
    'Fill': <FillOrShort typeQuestion={typeQuestion} setDetails={setDetails} questionDetails={questionDetails}/>,
    'Judge': <Judge setDetails={setDetails} questionDetails={questionDetails}/>,
    'Short': <FillOrShort setDetails={setDetails} questionDetails={questionDetails}/>,
    'Subsystem': <Subsystem setDetails={setDetails} questionDetails={questionDetails}/>
  }

  return (
    <ModalForm
      width={1000}
      form={formObj}
      preserve={false}
      title={(questionDetails.id === undefined ? '添加' : '修改') + type[typeQuestion || questionDetails.type]}
      visible={isModalShow}
      onVisibleChange={setIsModalShow}
      onFinish={createOrEditQuestion}
      style={{ zIndex: 100000 }}
    >
      {
        /** 母题id **/
        subsystemId === undefined ? '' : <ProFormText name="pid" initialValue={subsystemId.id} hidden={true}/>
      }
      {
        /** 题目id **/
        questionDetails.id === undefined ? '' : <ProFormText name="id" initialValue={questionDetails.id} hidden={true}/>
      }

      {/* 题目类型 */}
      <ProFormText name="type" initialValue={typeQuestion || questionDetails.type} hidden={true}/>
      {/* 选择分类 */}
      <ProForm.Item required name="category_id" label="分类" initialValue={questionDetails.category_id}>
        <TreeSelect
          name="category_id"
          value={questionDetails.category_id}
          treeDefaultExpandAll
          treeData={category}/>
      </ProForm.Item>
      {/* 题干 */}
      <ProFormGroup>
        <ProForm.Item
          label="题干"
          required
          name="content"
          initialValue={questionDetails.content === undefined ? '' : questionDetails.content}
        >
          <EditorDemo
            setDetails={setDetails}
            name="content"
            content={
              (
                (strComponents === 'Fill' && questionDetails.content === undefined)
                  ? '例: 西游记中的大徒弟有[*][*][*]'
                  : (strComponents !== 'Fill' && questionDetails.content !== undefined) ? questionDetails.content : ''
              )
            }/>
        </ProForm.Item>
      </ProFormGroup>
      {/* 渲染组件 */}
      {
        typeComponents[strComponents]
      }
      {/* 题目状态,题目难度,分数 */}
      <ProFormGroup>
        <ProFormRadio.Group
          label="题目状态"
          required
          initialValue={questionDetails.status || 0}
          name="status"
          options={[
            {
              value: 0,
              label: '未审核'
            },
            {
              value: 1,
              label: '审核通过'
            }
          ]}
        />
        <ProFormRate name="level" label="题目难度" initialValue={questionDetails.level || 1} colon={false}
                     allowClear={false}/>
        <ProFormDigit name="fraction" label="分数" initialValue={questionDetails.fraction || 1} width="sm" min={1}
                      max={50}/>
      </ProFormGroup>
    </ModalForm>
  )
}

export default Create
